<?php
namespace app\portal\controller;

use cmf\controller\AdminBaseController;
use app\portal\model\PortalPostModel;
use app\portal\service\PostService;
use app\portal\model\HouseFieldTypeCategory;
use app\portal\model\HouseFieldType;
use think\Db;
use app\admin\model\ThemeModel;

class AdminHouseParameterController extends AdminBaseController
{

    public function default () {
    }

    public function index()
    {
      $categorys = HouseFieldTypeCategory::all();
      $list = HouseFieldType::with('param')->select();
      $houses = [];
      $this->assign('list', $list);
      $this->assign('categorys', $categorys);
      return $this->fetch();
    }

    public function add()
    {
      return $this->fetch();
    }

    public function addForm () {
      if (!$this->request->isPost()) {
        return;
      }

      if (!isset($_POST['catid']) || !preg_match("/^\d+$/", $_POST['catid'])) {
        $this->error("请选择参数类型！");
      }

      if (!isset($_POST['name']) || $_POST['name'] == '') {
        $this->error("参数不正确！");
      }

      $fieldType = new HouseFieldType();
      $fieldType->catid = $_POST['catid'];
      $fieldType->name = $_POST['name'];
      $fieldType->save();
      $this->success("参数添加成功！", '');
    }

    public function edit() {
      $param = $this->request->param();

      if (!isset($param['id'])) {
        $this->error('参数不合法！');
      }

      $data = HouseFieldType::find($param['id']);
      $categorys = HouseFieldTypeCategory::all();

      $this->assign('data', $data);
      $this->assign('categorys', $categorys);

      return $this->fetch();
    }

    public function editForm() {
      if (!$this->request->isPost()) {
        return;
      }

      $param = $this->request->param();

      if (!isset($param['id'])) {
        $this->error("参数不正确！");
      }

      if (!isset($_POST['catid']) || !preg_match("/^\d+$/", $_POST['catid'])) {
        $this->error("请选择参数类型！");
      }

      if (!isset($_POST['name']) || $_POST['name'] == '') {
        $this->error("参数不正确！");
      }

      $fieldType = HouseFieldType::get($param['id']);
      $fieldType->catid = $_POST['catid'];
      $fieldType->name = $_POST['name'];
      $fieldType->save();
      $this->success("参数修改成功！", '');
    }

    public function delete() {
      $param = $this->request->param();

      if (!isset($param['id'])) {
        $this->error('参数不合法！');
      }

      $res = HouseFieldType::destroy($param['id']);
      if ($res) {
        $this->success('删除成功');
      } else {
        $this->error('删除失败');
      }
    }

}
